package com.tk.exam.exception;

import com.tk.exam.http.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


@ControllerAdvice
@Slf4j
public class ControllerExceptionAdvice {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Response handleDefaultException(Exception ex) {
        ex.printStackTrace();
        String name = ex.getClass().getName();
        if (name.equals("org.springframework.web.method.annotation.MethodArgumentTypeMismatchException")) {// -- 传参类型错误！
            log.error("传参类型错误！", ex);
            return Response.fail("传参类型错误！");
        } else if (ex instanceof MissingServletRequestParameterException) {
            log.error("缺少参数", ex);
            return Response.fail("缺少参数");
        } else if (name.equals("org.springframework.web.HttpRequestMethodNotSupportedException")) {
            log.error("请求方式错误", ex);
            return Response.fail("请求方式错误");
        } else if (name.equals("org.springframework.http.converter.HttpMessageNotReadableException")) {
            log.error("requestBody参数缺少", ex);
            return Response.fail("requestBody参数缺少");
        } else {
            log.error("系统异常", ex);
            return Response.fail("系统错误");
        }

    }

    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Response handleHttpException(HttpMediaTypeNotSupportedException ex) {
        log.warn("不支持的content type", ex.getMessage());
        return Response.fail("请求方式错误");
    }

    @ExceptionHandler({ApiException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Response handleApiException(ApiException ex) {
        log.warn(ex.getMessage());
        return Response.fail(ex.getMessage());
    }

}
